﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Extensions.Logging;
using iot.Protocol;
using iot.Protocol.Modbus;
using iot.Models;
using System.Net.Sockets;
using Modbus.Device;

namespace iot.pages
{
    public partial class ModbusControl : UserControl
    {
        Form form;
        public ModbusControl(Form form)
        {
            InitializeComponent();
            this.input1.Text = "127.0.0.1";
            this.input2.Text = "502";
            this.input3.Text = "100";
            this.input4.Text = "100";
            this.form = form;
        }

        IPrototol prototol = null;
        public bool bConnected { get; set; }
      
        private void ModbusControl_Load(object sender, EventArgs e)
        {

        }

        private void gridPanel1_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Use 'await' to ensure the Connect method is awaited properly
            prototol = new ModbusTcpClientNet();
            PlcInfo plcInfo = new PlcInfo();
            plcInfo.IP = input1.Text;
            plcInfo.PORT = input2.Text;
            if (prototol.Connect(plcInfo))
            {
                AntdUI.Message.success(form, "连接成功", Font);
                bConnected = true;
            }
            else
            {
                AntdUI.Message.error(form, "连接失败", Font);
                bConnected = false;
            }
        }


     

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                //prototol.ReadData(new PointInfo { address = "39768" });
                //AntdUI.Message.success(form, "读取成功", Font);
                
            }
            catch (Exception ex) { 
               throw new Exception(ex.Message);
            }
            //ModbusTCP modbusTCP = new ModbusTCP("127.0.0.1", 502);
            //byte address = byte.Parse("100");
            //ModbusResultModel<int> modbusResultModel = modbusTCP.ReadHoldingRegister<int>(1, 1, ModbusFunctionCode.ReadRegister, 101);
        
        }

        private void button3_Click(object sender, EventArgs e)
        {
                AntdUI.Message.success(form, "写入成功", Font);
        }
    }
}
